# Dungeon mode handler

#   Akalabeth Re-Bourne
#   Copyright (C) 2008 Norman B. Lancaster
#
#    This program is free software: you can redistribute it and/or modify
#   it under the terms of the GNU General Public License as published by
#   the Free Software Foundation, either version 3 of the License, or
#   (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#   but WITHOUT ANY WARRANTY; without even the implied warranty of
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#   GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#   along with this program.  If not, see http://www.gnu.org/licenses/

# PC state
declare dmPCX=0
declare dmPCY=0
declare dmPCD=E

# Render state variables
declare dmRDung=1

# Main dungeon mode routine, uses the currently loaded map and pre-set PC values
function DMDungeonMode
{
	ATClear

	# Command processing loop
	while :; do
		DMUpdateScreen
		ATGetCh
		
		# Command dispatch
		case $gReturnValue in
			( UP | 8 ) DMForward; dmRDung=1 ;;
			( LEFT | 4 ) DMTurn L; dmRDung=1 ;;
			( RIGHT | 6 ) DMTurn R; dmRDung=1 ;;
			( DOWN | 2 ) DMTurn L; DMTurn L; dmRDung=1 ;;
			1 ) DMTurn L; DMForward; DMTurn R; dmRDung=1 ;;
			3 ) DMTurn R; DMForward; DMTurn L; dmRDung=1 ;;
			0 ) DMTurn R; DMTurn R; DMForward; DMTurn R; DMTurn R; dmRDung=1 ;;
			ESC ) break ;;
			* )
				ATGoto 48 2
				echo -nE "Unknown input string: \"$gReturnValue\"                            "
		esac
	done
	
	return 0
}

# Move the player forward
function DMForward
{
	local tX=$dmPCX tY=$dmPCY tNum oNum
	
	# Do the move
	case $dmPCD in
		N ) (( tY=dmPCY-1 )) ;;
		E ) (( tX=dmPCX+1 )) ;;
		S ) (( tY=dmPCY+1 )) ;;
		W ) (( tX=dmPCX-1 )) ;;
	esac
	
	# Map interaction
	MIGetTile $tX $tY
	tNum=$gReturnValue
	MIGetFlag $tNum W
	if (( gReturnValue==0 )); then
		# Player cannot walk here
		return 0
	fi
	
	# Object interaction
	OIGetObject $tX $tY
	oNum=$gReturnValue
	if (( oNum >= 0 )); then
		OIGetFlag $oNum W
		if (( gReturnValue==0 )); then
			# Player cannot walk here
			return 0
		fi
	fi
	
	# Commit the move
	dmPCX=$tX
	dmPCY=$tY
	
	return 0
}

# Turns the player left or right
# $1 Direction (L, R)
function DMTurn
{
	if [[ "$1" == "L" ]]; then
		case $dmPCD in
			N ) dmPCD=W ;;
			E ) dmPCD=N ;;
			S ) dmPCD=E ;;
			W ) dmPCD=S ;;
		esac
	elif [[ "$1" == "R" ]]; then
		case $dmPCD in
			N ) dmPCD=E ;;
			E ) dmPCD=S ;;
			S ) dmPCD=W ;;
			W ) dmPCD=N ;;
		esac
	else
		echo "EE DMTurn Invalid direction passed" 1>&2
		exit 1
	fi
	
	return 0
}

# Renders parts of the screen based on the dmR* variables
function DMUpdateScreen
{
	# Call render routines
	if (( dmRDung > 0 )); then DVRenderDungeon $dmPCX $dmPCY $dmPCD; fi
	
	# Clear render flags
	dmRDung=0
	
	return 0
}

